import { defineStore } from "pinia";
import videojs from 'video.js'

import { isRef } from "vue";

export const useVideoPlay = defineStore('VideoPlay', {
    states:()=> {
        return {
            // 播放地址
            playUrl:'',
        }
    },
    actions: {
        /**
         * 视频解析为source格式
         * @param {*播放地址} url 
         * @returns
         */
        videoUrlToSource(url) {
            let type = ''
            const lastKey = url.split('.').pop()
            switch (lastKey) {
                case 'm3u8': {
                    type = 'application/x-mpegURL';
                    break;
                }
                case 'mp4': {
                    type = 'video/mp4'
                    break;
                }
                default: {
                    type = `video/${lastKey}`
                    break;
                }
            }
            return {
                src: url,
                type
            }
        },
        getVideo(el, url) {
            if ((!el && !isRef(el)) || !url) return
            const div = document.getElementById("videoDiv")
            div.innerHTML = ""
            div.innerHTML = `<video id="my-video" class="video-js"></video>`
            const options = {
              autoplay: true, // 设置自动播放
              controls: true, // 显示播放的控件
              // errorDisplay: false,
              muted: true,
              sources: [
                // 如果需要切换视频源，src需要动态设置
                {
                  src: this.playUrl,
                  type: "application/x-mpegURL", // 告诉videojs,这是一个m3u8流
                },
              ],
            };
            // videojs的第一个参数表示的是，文档中video的id
            videojs("my-video", options, function onPlayerReady() {
              console.log("我在播放中...")
            })
        }
    }
})